<template>
  <div class="addHoliday">
    <div class="calendar">
      <vue-better-calendar
        v-if="show"
        :events="checkText"
        ref="calendar"
        mode="multi"
        @select-multi-date="selectDate"
        @next="nextDateTime"
        @prev="downDateTime"
        @select-month="selectMonth"
        @select-year="selectYear"
      />
    </div>
    <div class="menuList">
      <el-button class="btn" type="primary" v-throttle="[save]">保存</el-button>
      <br />
      <el-button class="btn" type="info" @click="reset">重置</el-button>
      <br />
      <el-button class="btn" @click="returns">返回</el-button>
      <br />
    </div>

    <history-routes ref="historyRoutes" style="display: none"></history-routes>
  </div>
</template>

<script>
import VueBetterCalendar from 'vue-better-calendar'
import axios from 'axios'
import historyRoutes from '@/layout/history-routes'
export default {
  name: "index",
  components: { VueBetterCalendar, historyRoutes },
  data () {
    return {
      checkText: {},
      selectedDate: [],
      htDate: [],
      htDatekey: [],
      month: '',
      year: '',
      show: true,
      weeks: ['日', '一', '二', '三', '四', '五', '六']
    }
  },
  created () {
    this.month = new Date().getMonth() + 1;
    this.year = new Date().getFullYear();
    this.getList(this.month, this.year);
  },

  methods: {
    returns () {
      this.$refs.historyRoutes.closeTab('current');
      this.$router.push({
        path: "jiejiari",
      })
    },
    reload () { // 重置选择器
      this.$refs.calendar.multiDays = [];
    },
    reset () {
      this.getList(this.month, this.year);
      this.htDate = [];
      this.htDatekey = [];
      this.selectedDate = [];
      this.reload()
    },
    save () {
      var hdate = '';

      var key = [];
      for (var i = 0; i < this.selectedDate.length; i++) {
        if (key.indexOf(this.selectedDate[i]) === -1) {
          key.push(this.selectedDate[i])
          var n = this.selectedDate[i].substring(0, this.selectedDate[i].indexOf('-'));
          var y = this.selectedDate[i].substring(this.selectedDate[i].indexOf('-') + 1, this.selectedDate[i].lastIndexOf('-'));
          var r = this.selectedDate[i].substring(this.selectedDate[i].lastIndexOf('-') + 1);
          if (y < 10) {
            y = "0" + y;
          }
          if (r < 10) r = "0" + r;

          if (i == 0) {
            hdate = n + "-" + y + "-" + r
          } else {
            hdate += "SPLIT" + n + "-" + y + "-" + r
          }
        }
      }
      const loading = this.$loading({
        lock: true,
        text: '数据处理中'
      });
      var thta = this;
      const config = {
        headers: { 'Content-Type': 'application/json' }
      };
      var moth = this.month
      if (moth < 10) moth = "0" + moth
      axios.post("/api/holidayConf", {
        hmonth: this.year + "-" + moth,
        hdate: hdate,
        hyear: this.year
      }, config).then(response => {
        if (response.data.msg == "操作成功") {
          this.$message.success(response.data.msg)
        } else {
          this.$message.success("操作失败")
        }
        this.reload()
        thta.getList(this.month, this.year);
        loading.close()
      }).catch(e => {
        loading.close()
        this.$message.error('保存失败')
      })
    },
    selectYear (year) {  // 选择年份
      this.year = year;
      this.getList(this.month, this.year);
      this.reload()
    },
    selectMonth (month, year) {  // 选择月份
      this.month = month;
      this.year = year;
      this.getList(this.month, this.year);
      this.reload()
    },
    nextDateTime (month, year) { // 选择下一个月
      this.month = month;
      this.year = year;
      this.getList(this.month, this.year);
      this.reload()
    },
    downDateTime (month, year) {// 选择上一个月
      this.month = month;
      this.year = year;
      this.getList(this.month, this.year);
      this.reload()
    },
    // 页面加载
    getList (month, year) {

      this.checkText = {}
      this.htDate = []
      this.selectedDate = []
      if (month < 10) {
        month = "0" + month
      }
      const loading = this.$loading({
        lock: true,
        text: '数据处理中'
      });
      const config = {
        headers: { 'Content-Type': 'application/json' }
      };
      axios.get("/api/holidayConf/getEditHolidayQuery/" + year + "-" + month).then(response => {
        this.htDate = response.data.data;
        this.selectFormData(this.htDate)

        loading.close()
      }).catch(e => {
        loading.close()
      })

    },
    selectFormData (date) {
      for (var i = 0; i < date.length; i++) {
        this.selectedDate.push(date[i].hdate);
      }
      // 如果没有被设置 过，就默认周六周日
      if (date.length === 0) {
        this.getWeeksWithYearAndMonth(this.year, this.month)
      }
    },
    _dateFormate (date) { // 日期 去掉 0
      let result = '';
      for (var i = 0; i < date.length; i++) {
        result += Number(date[i]) + '-'
      }
      return result.substring(0, result.length - 1)
    },
    selectDate (dateList) {

      this.checkText = {}
      this.selectedDate = [];
      this.selectFormData(this.htDate);
      for (var i = 0; i < dateList.length; i++) {
        if (this.selectedDate.indexOf(this._dateFormate(dateList[i])) >= 0) {
          this.selectedDate.splice(this.selectedDate.indexOf(this._dateFormate(dateList[i])), 1)
          this.checkText[this._dateFormate(dateList[i])] = {}
        } else {
          this.selectedDate.push(this._dateFormate(dateList[i]))
        }

      }
    },
    getWeeksWithYearAndMonth (years, month) {
      var yearsMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
      if ((years % 4 == 0 && years % 100 != 0) || (years % 400 == 0)) { // 如果是 闰年
        yearsMonth[1] = 29
      }
      for (var i = 1; i <= yearsMonth[month - 1]; i++) {
        var k = new Date(years, month - 1, i);
        if (k.getDay() === 0 || k.getDay() === 6) {
          // 如果=== -1 证明没有
          if (this.selectedDate.indexOf(years + "-" + month + "-" + i) === -1) {
            this.selectedDate.push(years + "-" + month + "-" + i);
          }
        }
      }
    },

  },
  watch: {
    selectedDate () {
      this.checkText = {};
      for (var i = 0; i < this.selectedDate.length; i++) {
        this.checkText[this.selectedDate[i]] = {
          className: 'check-in',
          title: '休假',
          styles: {
            color: 'red',
            backgroundColor: '#bf7fba'
          }
        }
      }
    }


  }
}
</script>

<style scoped lang="scss">
.addHoliday {
  display: flex;
  justify-content: center;
  align-items: center;
  .calendar {
    width: 46%;
    background-color: #fff;
    /deep/ .calendar-day {
      max-height: 100px;
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      &.check-in {
        color: red !important;
        background-color: ghostwhite !important;
      }
      &.disabled {
        background-color: #f5f5f5;
      }
    }
  }
  /deep/ .vue-better-calendar {
    .calendar-header
      .calendar-ctl
      .calendar-ctl-month
      .month
      .select-month-panel
      .item {
      font-size: 16px;
    }
    .calendar-header .calendar-ctl .calendar-ctl-month .year {
      font-size: 13px;
    }
    .calendar-header .calendar-ctl .calendar-btn {
      cursor: pointer;
    }
    .calendar-body .calendar-dates .date-row ul .calendar-day {
      .text {
        font-size: 16px;
        &.text-custom-day,
        &.text-fest-day {
          font-size: 12px;
        }
      }
      .text {
        &.text-custom-day {
          font-size: 16px;
          color: dodgerblue;
        }
      }
    }
  }
  .menuList {
    margin-left: 5%;
  }
  .btn {
    margin: 10px auto;
    width: 320px;
    height: 60px;
    padding: 20px;
    border-radius: 6px;
  }
}
</style>
